﻿using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Request.Login;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.IOC;
using CRM.Infrastructure.Tools;
using CRM.Service.EFCore;
using CRM.Service.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM.Service.Instance
{
    [Inject_]
    public class Login_Service:Base_Service, I_Login_Service
    {
        private readonly Login_IOC _login_IOC;

        public Login_Service(Login_IOC login_IOC)
        {
            _login_IOC = login_IOC;
        }

        public async Task<SysUser?> Get_User_By_LastCode(string code, string ip)
        {
            var iq = _login_IOC._sys_Login_Log_EFCore.QueryAll(d => d.Llcode == code
          && d.Llip == ip);
            if (!await iq.AnyAsync())
            {
                return null;
            }
            var log = await iq.SingleAsync();
            var last = await _login_IOC._sys_Login_Log_EFCore.QueryAll(false, o => o.LlcreateTime, d => d.Lluid == log.Lluid).FirstAsync();

            if (log.Llid != last.Llid)
            {
                return null;
            }
            return await _login_IOC._sys_User_EFCore.QueryAll(d => d.Uid == log.Lluid).SingleAsync();
        }

        public async Task<Api_Response_Dto> logins(Login_Request_Dto dto)
        {
            var iq = _login_IOC._sys_User_EFCore.QueryAll(d => d.Uaccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return Result(0, "账号或密码错误");
            }
            var user = await iq.SingleAsync();
            if (user.UisActive == 0)
            {
                return Result(0, "账号未激活", new
                {
                    active = 0
                });
            }
            if (user.UisBan == 1)
            {
                return Result(0, "账号已禁用", new
                {
                    ban = 1
                });
            }
            var pwd = EncryptUtil.LoginMd5(dto.password!, user.Usalt!);
            if (user.Upassword != pwd)
            {
                return Result(0, "账号或者密码错误");
            }
            SysLoginLog sysLoginLog = new SysLoginLog()
            {
                Llid = Config.GUID(),
                Llcode = dto.code,
                LlcreateTime = DateTime.Now,
                Llexplain = null,
                Llip = Config.GetIp(),
                Llresult = 0,
                Lltype = "admin",
                Lluid = user.Uid,
            };
            _login_IOC._sys_Login_Log_EFCore.Add(sysLoginLog);
            _login_IOC._sys_Login_Log_EFCore.SaveChanges();
            return Result(1, "ok");
        }
    }
}
